package com.wing.productionPlan.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.enterprise.feign.EnterpriseClient;
import com.wing.enterprise.product.model.response.ProductDetailVO;
import com.wing.enterprise.sell.model.entity.Order;
import com.wing.enterprise.sell.model.response.OrderVO;
import com.wing.productionPlan.model.entity.DemandPlan;
import com.wing.productionPlan.model.entity.DemandPlanRecord;
import com.wing.productionPlan.model.entity.ProductionPlan;
import com.wing.productionPlan.model.request.ProductionTypeForm;
import com.wing.productionPlan.model.response.DemandPlanVO;
import com.wing.productionPlan.model.response.ProductionPlanVO;
import com.wing.productionPlan.service.DemandPlanRecordService;
import com.wing.productionPlan.service.DemandPlanService;
import com.wing.productionPlan.service.ProductionPlanService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.excel.DemandPlanExcelln;
import com.wing.web.excel.DownExcelUtil;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.UseInventoryUserExcelIn;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Transient;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@Validated
@Api(value = "Admin-生产管理-需求计划表", tags = "#/product/demandPlan/demandPlanList")
@RestController("demandPlanController")
@RequestMapping("productionPlan/admin/demandPlan")
@RequiredArgsConstructor
public class DemandPlanController {

    private final DemandPlanService demandPlanService;

    private final DemandPlanRecordService planRecordService;

    @ApiOperation(value = "查研发任务列表", notes = "搜索-任务")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<DemandPlanVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String customerName
            ,String purchaseTissue
            ,String skuCode
            ,String startTime
            ,String endTime
    ) {
        Page<DemandPlanVO> pg = new Page<>(page, limit);
        Map map = new HashMap();
        map.put("purchaseTissue", purchaseTissue);
        map.put("customerName", customerName);
        map.put("skuCode", skuCode);
        map.put("startTime", startTime);
        map.put("endTime", endTime);
        Page<DemandPlanVO> list = demandPlanService.pageList4app(pg, map);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    /**
     * 下载产品数据录入excel模板
     */
    @ApiOperation(value = "下载产品数据录入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String[] headerArr = {"工厂名称","物料编码","物料描述","采购组织","采购组名称","物料单位",
                "物料类型","计划接收时间","供应商编码","三方仓库存","近三个月平均到货","计划时间","预测需求数"};
        List<String[]> downData = new ArrayList<>();
        DownExcelUtil.createExcelTemplate(response, request, "需求计划导入模板", Arrays.asList(headerArr),downData, null);
    }

    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("上传文件为空！");
        }
        try {
            //获取原始的文件名
            ExcelUtil<DemandPlanExcelln> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<DemandPlanExcelln> list = reader.read(is,DemandPlanExcelln.class);

            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            demandPlanService.importExcel(list);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("上传文件异常！异常信息:", e);
            return JsonResult.exception("上传文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("上传成功！");
    }


    @ApiOperation(value = "添加需求计划表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody DemandPlan demandPlan) {

        demandPlan.setCreator(JwtUtils.getLoginUserId());
        demandPlan.setModifier(JwtUtils.getLoginUserId());
        demandPlan.setCreateTime(LocalDateTime.now());
        demandPlan.setCreatorName(JwtUtils.getLoginUsername());
        if (demandPlanService.save(demandPlan)) {
            if(CollectionUtils.isNotEmpty(demandPlan.getPlanRecords())){
                demandPlan.getPlanRecords().forEach(pr ->{
                    pr.setDemandPlanId(demandPlan.getId());
                    pr.setCreator(JwtUtils.getLoginUserId());
                    pr.setModifier(JwtUtils.getLoginUserId());
                    pr.setCreateTime(LocalDateTime.now());
                    pr.setCreatorName(JwtUtils.getLoginUsername());
                });
                planRecordService.saveBatch(demandPlan.getPlanRecords());
            }
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "查询需求计划明细", notes = "搜索")
    @GetMapping("/get")
    public JsonResult get(@RequestParam("id") Long id) {
        DemandPlanVO appById = demandPlanService.get4appById(id);
        appById.setPlanRecords(planRecordService.pageList4app(appById.getId()));
        return JsonResult.success(appById);
    }

    @ApiOperation(value = "修改产品明细表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody DemandPlan demandPlan) {
        DemandPlan productDetail = demandPlanService.getById(demandPlan.getId());
        if (productDetail == null) {
            return JsonResult.fail("修改失败！");
        }
        if (demandPlanService.updateById(demandPlan)) {
            if (CollectionUtils.isNotEmpty(demandPlan.getPlanRecords())) {
                QueryWrapper<DemandPlanRecord> wrapper = new QueryWrapper<>();
                wrapper.lambda().eq(DemandPlanRecord::getDemandPlanId,productDetail.getId());
                planRecordService.remove(wrapper);
                demandPlan.getPlanRecords().forEach(pr -> {
                    pr.setDemandPlanId(demandPlan.getId());
                });
                planRecordService.saveBatch(demandPlan.getPlanRecords());
            }
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

}
